import {messages} from "share/common";
/**
 * Created by Allen on 2018/1/15.
 */
import React from 'react'
import { connect } from 'react-redux'
import menuRoute from 'routes/menuRoute'
import { Tabs, Input, Row, Col, Spin } from 'antd';
import travelPolicyService from 'containers/expense-reimbursement-control/expense-standard/travel-policy/travel-policy.service'
import 'styles/expense-reimbursement-control/expense-standard/travel-policy/travel-standard.scss'
import planeImg from 'images/plane.png'
import trainImg from 'images/train.png'
import hotelImg from 'images/hotel.png'
import diningImg from 'images/dining.png'
import carImg from 'images/car.png'
const TabPane = Tabs.TabPane;
const Search = Input.Search;
import defaultExpenseTypeIcon from 'images/expense/default-expense-type.png'
import ResizeTable from 'components/resize-table'

class TravelStandard extends React.Component{
  constructor(props) {
    super(props);

    this.state = {
      loading: false,
      subsidyLoading:false,
      status: 'STANDARD',
      data: [],
      page: 0,
      pageSize: 10,
      columns:[
        {title: messages('common.sequence'), dataIndex: 'index', width: 48}, //序号
        {title: messages('setting.key1194'/*图标*/), dataIndex: 'imgUrl', width: '15%', render: (value) => (
          <img src={value} alt="" style={{display: 'block', margin: '0 auto', maxWidth: 40}}/>
        )}, //图标
        {title: messages('setting.key1195'/*差旅类型*/), dataIndex: 'type'}, //差旅类型
        {title: messages('setting.key1190'/*差旅标准规则*/), dataIndex: 'rules'} //差旅标准规则
      ],
      pagination: {
        total: 0
      },
      rulesList: menuRoute.getRouteItem('rules-list','key'),
      diningList: menuRoute.getRouteItem('dining-list', 'key'),
      travelSubsidyDetail: menuRoute.getRouteItem('travel-subsidy-detail','key'),
      cityLevel:menuRoute.getRouteItem('city-group','key'),
      rulesListSet: menuRoute.getRouteItem('travel-policy','key'),
      setOfBooks: [],
      nowSetOfBooks: {
        id: '',
        setOfBooksName: ''
      },
    };
  }

  componentWillReceiveProps(nextProps) {
    if (nextProps.nowSetOfBooks.id !== this.props.nowSetOfBooks.id && this.props.tenantMode) {
      this.setState({
        nowSetOfBooks: nextProps.nowSetOfBooks
      }, () => {
        this.getList();
      })
    }
  };

  componentDidMount() {
    this.setState({
      nowSetOfBooks: this.props.nowSetOfBooks
    }, () => {
      this.getList();
    });
  }

  //得到值列表数据
  getList(){
    const {tenantMode} = this.props;
    this.setState({ loading: true });
    travelPolicyService.getTravelStandardList({setOfBooksId: tenantMode ? this.state.nowSetOfBooks.id : undefined}).then((response)=>{
      response.data.forEach((item, index)=>{
        if (item.travelType === 1001){
          item.type = messages('setting.key686'/*机票*/);
          item.imgUrl = planeImg;
        } else if (item.travelType === 1002){
          item.type = messages('setting.key717'/*火车*/);
          item.imgUrl = trainImg
        } else if (item.travelType === 1003){
          item.type = messages('setting.key707'/*酒店*/);
          item.imgUrl = hotelImg
        } else if (item.travelType === 1010){
          item.type = messages('expense-reimbursement-control.key109')/*用餐*/;
          item.imgUrl = diningImg;
        } else if (item.travelType === 1008){
          item.type = messages('expense-reimbursement-control.key110')/*用车*/;
          item.imgUrl = carImg;
        }
        item.index = this.state.page * this.state.pageSize + index + 1;
        item.key = item.index;
        item.rules = `${item.ruleNumber} ${messages('setting.key1196'/*条*/)}`;
      });
      this.setState({
        data: response.data,
        loading: false,
        pagination: {
          total: Number(response.data.length),
          onChange: this.onChangePager
        }
      })
    });
  }

  //获取补贴类型列表
  getExpenseList(){
    const { company }= this.props;
    this.setState({subsidyLoading: true});
    travelPolicyService.getTravelSubsidyList(company.companyOID).then((resp) => {
        this.setState({
          expenseTypeData: resp.data.filter(item=> item.readonly === false),
          subsidyLoading: false
        })
      })
  }

  //分页点击
  onChangePager = (page) => {
    if (page - 1 !== this.state.page)
      this.setState({
        page: page - 1
      }, ()=>{
        this.getList();
      })
  };

  toCityLevel = ()=>{
    this.context.router.push(this.state.cityLevel.url)
  }

  handleRowClick = (record) => {
    const { tenantMode } = this.props;
    const { nowSetOfBooks, rulesList, diningList } = this.state;
    let url = '';
    if (record.travelType === 1010) {
      //用餐类型跳这个
      url = diningList.url.replace(':travelItineraryStandID', record.id).replace(':id', record.travelType);
    } else {
      url = rulesList.url.replace(':travelItineraryStandID', record.id).replace(':id', record.travelType);
    }
    if (tenantMode) {
      url = url.replace(':setOfBooksId', nowSetOfBooks.id);
    }
    this.context.router.push(url);
  };

  handleColClick(item) {
    this.context.router.push({
      pathname: this.state.travelSubsidyDetail.url,
      state: {typeId: item.expenseTypeOID,type: item.name}});
  };

  render(){
    const { columns, data, loading, pagination, status,subsidyLoading} = this.state;

    return (
      <div className="travel-policy">
        {status === 'STANDARD' && (
          <div className="travel-standard">
            <div className="table-header">
              <div className="table-header-title">{messages('common.total',{total: pagination.total})}</div>{/*共total条数据*/}
            </div>
            <ResizeTable
              columns={columns}
              dataSource={data}
              pagination={false}
              loading={loading}
              onRow={record => ({onClick: () => {this.handleRowClick(record)}})}
              bordered
              size="middle"
            />
          </div>
        )}

        {status === 'SUBSIDY' && this.state.expenseTypeData && (
          <Spin spinning={subsidyLoading}>
          <div className="travel-subsidy">
            <div className="travel-subsidy-title">{messages('setting.key1198'/*设置前请先前往*/)} <a onClick={this.toCityLevel}>{messages('setting.key1199'/*城市级别*/)}</a> {messages('setting.key1200'/*设置不同级别的城市分类*/)}</div>
            <Row className="row">
              {this.state.expenseTypeData.map((item,index) => {
                return (
                  <Col span="3" className="item-container" key={item.id} value={item}>
                    <div className="content" key={item.id}>
                      <div className="content-item" onClick={() =>this.handleColClick(item)}>
                        <img src={item.iconURL} onError={e => e.target.src = defaultExpenseTypeIcon} alt=""/>
                        <p>{item.name}</p>
                        {item.ruleTotal>1 && <div className='rule-text'>{item.ruleTotal}{messages('setting.key1201'/*条规则*/)}</div>}
                        {item.ruleTotal ===1 && <div className='rule-text'>{item.ruleTotal}{messages('setting.key1202'/*条规则*/)}</div>}
                      </div>
                    </div>
                  </Col>
                  )
                })}
            </Row>
          </div>
          </Spin>
        )}
      </div>
    )
  }
}

TravelStandard.propTypes = {
  nowSetOfBooks: React.PropTypes.object
};

TravelStandard.contextTypes = {
  router: React.PropTypes.object
};

function mapStateToProps(state) {
  return {
    company: state.login.loginCompany,
    tenantMode: state.main.tenantMode
  }
}

export default connect(mapStateToProps)(TravelStandard)
